package com.youwatch.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: kss
 * @Description:
 * @Date: Create in 2019/1/16
 */
@Slf4j
public class SynchronizedExample1 {

    // 修饰代码块-大括号括起来的代码，作用于调用对象
    public void test1() {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("test1 - {}", i);
            }
        }
    }

    // 修饰代码块-大括号括起来的代码，作用于调用对象
    public void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("test1 {} - {}", j, i);
            }
        }
    }

    // 修饰一个方法-整个方法，作用于调用对象-Synchronized方法不向下传递（子类继承不了），原因：Synchronized关键字不属于方法声明的一部分
    public synchronized void test2() {
        for (int i = 0; i < 10; i++) {
            log.info("test2 - {}", i);
        }
    }

    // 修饰一个方法-整个方法，作用于调用对象
    public synchronized void test2(int j) {
        for (int i = 0; i < 10; i++) {
            log.info("test2 {} - {}", j, i);
        }
    }

    public static void main(String[] args) {
        // 一个对象调用Synchronized关键字修饰代码块及普通方法
//        oneObject();

        // 多个对象调用Synchronized关键字修饰代码块及普通方法
        manyObject();
    }

    // 创建一个对象进行调用Synchronized关键字修饰代码块及普通方法
    private static void oneObject() {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> {
            example1.test1();
        });
        executorService.execute(() -> {
            example1.test1();
        });
        executorService.execute(() -> {
            example1.test2();
        });
        executorService.execute(() -> {
            example1.test2();
        });
    }

    // 创建多个对象进行调用Synchronized关键字修饰代码块及普通方法-结论：不同对象调用互相无影响
    private static void manyObject() {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();

        executorService.execute(() -> {
            example1.test1(1);
        });
        executorService.execute(() -> {
            example2.test1(2);
        });
//        executorService.execute(() -> {
//            example1.test2(1);
//        });
//        executorService.execute(() -> {
//            example2.test2(2);
//        });
    }
}
